package com.erp.products.inventory.service.impl;

import com.erp.common.utils.oss.AliyunOSSConstants;
import com.erp.products.addproduct.mapper.AddproductMapper;
import com.erp.products.inventory.domain.Inventory;
import com.erp.products.inventory.domain.InventoryVO;
import com.erp.products.inventory.mapper.InventoryMapper;
import com.erp.products.inventory.service.InventoryService;
import com.erp.products.productlist.domain.ErpProducts;
import com.erp.products.productlist.mapper.ProductListMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class InventoryServiceImpl implements InventoryService {
    @Autowired
    private InventoryMapper inventoryMapper;
    @Autowired
    private ProductListMapper productListMapper;


    @Override
    public List<InventoryVO> list(ErpProducts erpProducts) {
        List<InventoryVO> list1 = inventoryMapper.list(erpProducts);
        System.out.println("业务层接收的list1 = " + list1);
        list1.forEach(item -> {
            item.getErpProducts().setProductImage(AliyunOSSConstants.COMMON_URL + item.getErpProducts().getProductImage());
        });
        return list1;
    }

    @Override
    public List<String> getWarehouseList() {
        return inventoryMapper.getWarehouseList();
    }

    @Override
    @Transactional(rollbackFor = Exception.class) // 添加事务注解，指定异常回滚
    public String add(InventoryVO inventoryVo) {
        // 1. 检查商品是否存在
        ErpProducts product = productListMapper.selectErpProductsById(inventoryVo.getErpProducts().getProductId());
        System.out.println("商品product = " + product);
        if (product == null) {
            throw new IllegalArgumentException("商品不存在,请添加这个商品");
        }

        // 2. 插入库存记录
        System.out.println("发过来的inventoryVo = " + inventoryVo);
        int i = inventoryMapper.add(inventoryVo);
        if (i <= 0) {
            throw new IllegalArgumentException("库存记录插入失败");
        }

        // 3. 更新库存表的存入数量
//        int updateCount = productListMapper.updateInQuantity(
//                inventoryVo.getProductId(),
//                inventoryVo.getInQuantity()
//        );
//        if (updateCount <= 0) {
//            throw new IllegalArgumentException("商品库存更新失败");
//        }

        return "新增成功";
    }
}
